package com.mycompany.crm.controller;

import com.mycompany.crm.annotation.LogAnno;
import com.mycompany.crm.annotation.RequiredPermission;
import com.mycompany.crm.base.BaseController;
import com.mycompany.crm.base.ResultInfo;
import com.mycompany.crm.model.UserModel;
import com.mycompany.crm.query.UserQuery;
import com.mycompany.crm.service.UserService;
import com.mycompany.crm.utils.LoginUserUtil;
import com.mycompany.crm.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jy
 * @version 1.0
 * @date 2022/1/4 16:15
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController{

    @Resource
    private UserService userService;

    @LogAnno(description = "登录")
    @PostMapping("login")
    @ResponseBody
    public ResultInfo userLogin(HttpServletRequest request,String userName,String userPwd,String verifyCode){
        ResultInfo resultInfo = new ResultInfo();
        //调用service层登录方法
        UserModel userModel = userService.userLogin(request,userName, userPwd, verifyCode);
        //将返回的userModel对象设置到resultInfo对象中
        resultInfo.setResult(userModel);
        return resultInfo;
    }

    /**
     * 进入修改密码的页面
     * @return
     */
    @LogAnno(description = "进入修改密码的页面")
    @RequestMapping("toPasswordPage")
    public String toPasswordPage(){
        return "user/password";
    }

    /**
     * 修改密码
     * @param request
     * @param oldPassword
     * @param newPassword
     * @param repeatPassword
     * @return
     */
    @LogAnno(description = "修改密码")
    @PostMapping("updatePwd")
    @ResponseBody
    public ResultInfo updateUserPassword(HttpServletRequest request, String oldPassword,String newPassword,String repeatPassword){
        ResultInfo resultInfo = new ResultInfo();
        //获取cookie中的userId
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        //调用Service层修改密码的方法
        userService.updatePassword(userId,oldPassword,newPassword,repeatPassword);
        return resultInfo;
    }

    /**
     * 进入个人资料的页面
     * @return
     */
    @LogAnno(description = "进入个人资料的页面")
    @RequestMapping("toSettingPage")
    public String toSettingPage(HttpServletRequest request){
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        User user = userService.selectByPrimaryKey(userId);
        request.setAttribute("user",user);
        return "user/setting";
    }

    /**
     * 修改基本资料
     * @param request
     * @param userName
     * @param trueName
     * @param email
     * @param phone
     * @return
     */
    @LogAnno(description = "修改基本资料")
    @PostMapping("updateUserInfo")
    @ResponseBody
    public ResultInfo updateUserInfo(HttpServletRequest request, String userName,String trueName,String email,String phone,String userImg){
        ResultInfo resultInfo = new ResultInfo();
        //获取cookie中的userId
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        //调用Service层修改密码的方法
        userService.updateUserInfo(userId,userName,trueName,email,phone,userImg);
        return resultInfo;
    }

    /**
     * 修改头像
     * @param uploadFile
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @LogAnno(description = "修改头像")
    @RequestMapping(value="updatePersonalById")
    @ResponseBody
    public ResultInfo updatePersonalById(@RequestParam("file") MultipartFile uploadFile,HttpServletRequest request) throws IllegalStateException, IOException{
        ResultInfo resultInfo = new ResultInfo();
        String upload_path_prefix="public/images/uploadFile/";
        if(uploadFile.isEmpty()){
            //返回选择文件提示
            resultInfo.setMsg("请选择上传文件");
            return resultInfo;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
        String realPath = new String("src/main/resources/" + upload_path_prefix);
        System.out.println("-----------上传文件保存的路径【"+ realPath +"】-----------");
        //存放上传文件的文件夹
        File file = new File(realPath);
        System.out.println("-----------存放上传文件的文件夹【"+ file +"】-----------");
        System.out.println("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【"+ file.getAbsolutePath() +"】-----------");
        if(!file.isDirectory()){
            //递归生成文件夹
            file.mkdirs();
        }
        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
        String oldName = uploadFile.getOriginalFilename();
        System.out.println("-----------文件原始的名字【"+ oldName +"】-----------");
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
        System.out.println("-----------文件要保存后的新名字【"+ newName +"】-----------");
        try {
            //构建真实的文件路径
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            uploadFile.transferTo(newFile);
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/crm/images/uploadFile/" + newName;
            System.out.println("-----------【"+ filePath +"】-----------");
            resultInfo.setResult(filePath);
            return resultInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultInfo.setMsg("上传失败");
        return resultInfo;
    }


    /**
     * 查询所有的销售人员
     * @return
     */
    @LogAnno(description = "查询所有的销售人员")
    @RequestMapping("queryAllSales")
    @ResponseBody
    public List<Map<String,Object>> queryAllSales(){
        return userService.queryAllSales();
    }


    /**
     * 分页多条件查询用户列表
     * @param userQuery
     * @return
     */
    @LogAnno(description = "分页多条件查询用户列表")
    @RequiredPermission(code = "601002")
    @RequestMapping("list")
    @ResponseBody
    public Map<String,Object> selectByParams(UserQuery userQuery){
        return userService.queryByParamsForTable(userQuery);
    }

    /**
     * 进入用户列表界面
     * @return
     */
    @LogAnno(description = "进入用户列表界面")
    @RequestMapping("index")
    public String toIndex(){
        return "user/user";
    }

    /**
     * 进入添加/更新用户的界面
     * @return
     */
    @LogAnno(description = "进入添加/更新用户的界面")
    @RequestMapping("toAddOrUpdateUserPage")
    public String toAddOrUpdateUserPage(Integer id,HttpServletRequest request){
        //判断userId是否为空
        if (id != null){
            //通过Id查询用户数据便于回显
            User user = userService.selectByPrimaryKey(id);
            //将数据设置到请求域中
            request.setAttribute("userInfo",user);
        }
        return "user/add_update";
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @LogAnno(description = "添加用户")
    @RequiredPermission(code = "601001")
    @PostMapping("save")
    @ResponseBody
    public ResultInfo saveUser(User user){
        userService.saveUser(user);
        return success("用户添加成功!");
    }

    /**
     * 更新用户
     * @param user 传入的待更新的用户对象
     * @return
     */
    @LogAnno(description = "更新用户")
    @RequiredPermission(code = "601003")
    @PostMapping("update")
    @ResponseBody
    public ResultInfo updateUser(User user){
        userService.updateUser(user);
        return success("用户更新成功!");
    }

    /**
     * 删除用户
     * @param ids 页面传入的id，可能一个可能多个
     * @return
     */
    @LogAnno(description = "删除用户")
    @RequiredPermission(code = "601004")
    @PostMapping("delete")
    @ResponseBody
    public ResultInfo deleteUser(Integer[] ids){
        userService.deleteUserByIds(ids);
        return success("用户记录删除成功!");
    }

    /**
     * 查询所有的客户经理
     *
     * @param
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    @LogAnno(description = "查询所有的客户经理")
    @RequestMapping("queryAllCustomerManagers")
    @ResponseBody
    public List<Map<String,Object>> queryAllCustomerManagers(){
        return userService.queryAllCustomerManagers();
    }

}
